package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //登录
    @PostMapping("/employee/login")
    //接受参数
    public ResultInfo login(@RequestBody Map<String, String> param, HttpSession session) {
        //取出参数
        String username = param.get("username");
        String password = param.get("password");
        //判断是否登录成功
        ResultInfo login = employeeService.login(username, password);
        if (login.getCode() == 1) {
            //登录成功就将结果传到session中
            session.setAttribute(Constant.SESSION_EMPLOYEE, login.getData());
        }
        return login;
    }

    //显示列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name) {
        return ResultInfo.success(employeeService.findlist(name));
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session) {
        session.invalidate();
        return ResultInfo.success();
    }

    //添加用户
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.save(employee);
        return ResultInfo.success();
    }

    //修改前回显数据
    @GetMapping("/employee/{id}")
    public ResultInfo fingByid(@PathVariable("id") Long id) {
        //调用service
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    //修改
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        employeeService.update(employee);
        return ResultInfo.success();
    }
}
